from django.shortcuts import render
from rest_framework.viewsets import ReadOnlyModelViewSet
from .serializers import AreaSerializer,SubsAreaSerializer
from .models import Area
from rest_framework_extensions.cache.mixins import ListCacheResponseMixin,RetrieveCacheResponseMixin,CacheResponseMixin
# Create your views here.

class AreaViewSet(CacheResponseMixin,ReadOnlyModelViewSet):

    """
    list    GET /areas/infos/       获取省份
    retrieve GET /areas/infos/pk/   获取市，区，县
    """

    def get_serializer_class(self):

        if self.action == 'list':
            #返回省份的序列化器
            return AreaSerializer
        else:
            #返回市 区 县序列化器
            return SubsAreaSerializer

    def get_queryset(self):

        if self.action == 'list':
            #查询省份数据
            return Area.objects.filter(parent=None)
        else:
            # 返回所有数据， 系统会自己 根据 pk 信息 进行筛选
            return Area.objects.all()